package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.HelpInfoSingleDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/21.
 */

public class HelpinguserinfoActivity extends AppCompatActivity {

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.collapsingtoolbarlayout)
    CollapsingToolbarLayout collapsingtoolbarlayout;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.need_body_title)
    TextView needBodyTitle;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.money_tian)
    TextView moneyTian;
    @BindView(R.id.views_tv)
    TextView viewsTv;
    @BindView(R.id.worktype_dot)
    ImageView worktypeDot;

    @BindView(R.id.sex_dot)
    ImageView sexDot;

    @BindView(R.id.need_contentdescription)
    TextView needContentdescription;


    @BindView(R.id.scrollView)
    NestedScrollView scrollView;

    @BindView(R.id.swiperefresh)
    SwipeRefreshLayout swiperefresh;
    @BindView(R.id.cir_icon)
    CircleImageView cirIcon;
    @BindView(R.id.uname)
    TextView uname;
    @BindView(R.id.sex_iv)
    ImageView sexIv;
    @BindView(R.id.sex_tv)
    TextView sexTv;
    @BindView(R.id.sex_rl)
    RelativeLayout sexRl;
    @BindView(R.id.needtitle)
    TextView needtitle;
    @BindView(R.id.bottom_state)
    Button bottomState;
    @BindView(R.id.qianming)
    TextView qianming;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.peoplenum_tv)
    TextView peoplenumTv;
    @BindView(R.id.tools)
    TextView tools;
    @BindView(R.id.yuyuetime)
    TextView yuyuetime;
    @BindView(R.id.location)
    TextView location;
    private Dialog loadingdialog;
    //state 0未接单 1接单中 2完成接单成功
    public int state = 0;

    public int helpid = 0;
  private  String orderMoney="";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_helpinguserinfo);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();

    }

    private void initComponent() {
        helpid = getIntent().getIntExtra("helpid", 0);
        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset == 0) {
                    swiperefresh.setEnabled(true);
                } else {

                    swiperefresh.setEnabled(false);
                }
            }
        });
        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        swiperefresh.setColorSchemeColors(getResources().getColor(R.color.default_theme));
        swiperefresh.setProgressViewOffset(false, 0, DensityUtil.dip2px(150));
        swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initquery();
            }
        });
        initquery();
        initState();
    }


    @OnClick(value = {R.id.backbt})
    public void OnMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;


        }
    }


    public void initquery() {
        swiperefresh.setRefreshing(true);
        Map<String, String> map = new HashMap<>();
        map.put("helpid", "" + helpid);
        Xutils.POST(HttpUrl.userneedhelpquerybyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                swiperefresh.setRefreshing(false);
                Gson gson = new Gson();
                HelpInfoSingleDomain domain = gson.fromJson(result, HelpInfoSingleDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null) {
                            Glide.with(HelpinguserinfoActivity.this)
                                    .load(domain.getData().getUserAvatarpath())
                                    .asBitmap().centerCrop()
                                    .animate(R.anim.fade_in)
                                    .placeholder(R.drawable.nim_avatar_default)
                                    .into(new SimpleTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                            cirIcon.setImageBitmap(resource);
                                        }
                                    });

                            needtitle.setText(domain.getData().getUserName() + "需要帮助");
                            uname.setText(domain.getData().getUserName() + "");
                            if (domain.getData().getUserSex() == 0) {
                                sexRl.setBackgroundColor(getResources().getColor(R.color.defaule_qianblue));
                                sexIv.setImageResource(R.mipmap.sex_male_while);
                            } else {
                                sexRl.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                                sexIv.setImageResource(R.mipmap.sex_female_while);
                            }
                            sexTv.setText(domain.getData().getUserAge() + "");
                            if (TextUtils.isEmpty(domain.getData().getUserSigntext())) {
                                qianming.setText("这个人很懒，什么也没有留下");
                            } else {
                                qianming.setText("" + domain.getData().getUserSigntext());
                            }
                            phoneTv.setText("手机号码：" + domain.getData().getHelpIphone() + "");
                            peoplenumTv.setText("限定人数：" + domain.getData().getHelpPeoplenum() + "人");
                            needBodyTitle.setText("需求标题："+domain.getData().getHelpTitle() + "");
                            tools.setText("工具：" + domain.getData().getHelpTools());
                            money.setText( domain.getData().getHelpMoney()+"元");
                            viewsTv.setText("浏览量 " + domain.getData().getHelpWatchnum()+"人");
                            yuyuetime.setText(new SimpleDateFormat("MM月dd日HH时mm分").format(new Date(Tools.getStringtoDate(domain.getData().getHelpYuyuedatetime(),"yyyy-MM-dd HH:mm:ss"))));
                           location.setText(""+domain.getData().getHelpCity()+domain.getData().getHelpArea());
                            needContentdescription.setText(domain.getData().getHelpInfo()+"");
                            orderMoney=domain.getData().getHelpMoney();
                        }
                        break;

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                swiperefresh.setRefreshing(false);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void initState(){
        List<User> userList= Xutils.queryAll(getApplication(),User.class);
        Map<String,String> map=new HashMap<>();
          map.put("helpId",helpid+"");
        map.put("userId",userList.get(0).getUserId()+"");
        Xutils.POST(HttpUrl.userhelporderquerystate, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("*************"+result);
                try {
                    JSONObject jsonObject=new JSONObject(result);
                 switch (jsonObject.getInt("state")){
                     case HttpCode.SUCCESS:
                         state=jsonObject.getInt("data");
                          switch (state){
                              case 0:
                                  bottomState.setText("接单");
                                  bottomState.setClickable(true);
                                  bottomState.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View view) {
                                          addState();
                                      }
                                  });
                                  break;
                              case 1:
                                  bottomState.setText("接单中");
                                  bottomState.setClickable(false);
                                  bottomState.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View view) {
                                       Toast.makeText(getApplicationContext(),"接单中",Toast.LENGTH_SHORT).show();
                                      }
                                  });
                                  break;
                              case 2:
                                  bottomState.setText("接单完成");
                                  bottomState.setClickable(false);
                                  bottomState.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View view) {
                                          Toast.makeText(getApplicationContext(),"接单完成",Toast.LENGTH_SHORT).show();
                                      }
                                  });
                                  break;

                          }

                         break;
                 }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public void addState(){
        List<User> userList= Xutils.queryAll(getApplication(),User.class);
        Map<String,String> map=new HashMap<>();
        map.put("orderMoney",orderMoney+"");
        map.put("helpId",helpid+"");
        map.put("userId",userList.get(0).getUserId()+"");
        Xutils.POST(HttpUrl.userhelporderaddstate, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getApplicationContext(),""+jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")){
                        case HttpCode.SUCCESS:

                            bottomState.setText("接单中");
                            bottomState.setClickable(false);
                            bottomState.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            Toast.makeText(getApplicationContext(),"接单中",Toast.LENGTH_SHORT).show();
                                        }
                                    });
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
}
